package cn.botter.gateway.filter;

import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @BelongsProject: bo-club
 * @BelongsPackage: cn.botter.gateway.filter
 * @Author: 爱写Bug的Botter
 * @CreateTime: 2025-03-29:17:37
 * @Description: 描述
 * @Version: 1.0
 */
@Component
@Log4j2
public class LoginFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest.Builder mutate = request.mutate();
        String ip = request.getRemoteAddress().getAddress().getHostAddress();
        String path = request.getURI().getPath();
        if (log.isInfoEnabled()) {
            log.info("loginFilter.ip:{}, path:{}", ip, path);
        }
        //排除登录的请求
        if (path.equals("/user/doLogin")) {
            return chain.filter(exchange);
        }
        String loginId = StpUtil.getLoginId().toString();
        mutate.header("loginId", loginId);
        return chain.filter(exchange.mutate().request(mutate.build()).build()); //将mutate的request传入mutate的build，然后再build一下
    }
}
